//
//  NewLoginViewController.m
//  QXShowing
//
//  Created by 王道道 on 2018/4/20.
//  Copyright © 2018年 doll_dream. All rights reserved.
//

#define kTopMarginHeight   35
#define kLeftMarginHeight   20
#define kBgViewHeight   120+(kTopMarginHeight-20)*2

#import "NewLoginViewController.h"

#import "ForgetPswViewController.h"
#import "RegistViewController.h"

#import "ContactDataObject.h"

@interface NewLoginViewController ()

@property (nonatomic, strong) UITextField *phoneTF;
@property (nonatomic, strong) UITextField *pswTF;
@property (nonatomic, strong) UIButton *loginBtn;
@property (nonatomic, strong) UIButton *registBtn;
@property (nonatomic, strong) UIButton *forgetBtn;
@property (nonatomic, strong) UIImageView *photoImage;

@property (nonatomic, strong) SGUserModel *userModel;

@end

@implementation NewLoginViewController

#pragma mark - Lazy
- (SGUserModel *)userModel {
    if (_userModel == nil) {
//        _userModel = [[SGUserModel alloc]init];
        _userModel = [SGUserInfo getUserInfo];
    }
    return _userModel;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    self.title = @"登录";
    [self initLoginNavBar:@"登录"];
    self.view.backgroundColor = Bg_Color_F9F9F9;
    [self setUpUI];
    
    self.phoneTF.text = [BHSettingUtil dataAndStringIsNull:self.userModel.UserPhone]?@"":self.userModel.UserPhone;
    
//    [self initNavBarBackBtn];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setUpUI {
    self.photoImage = [[UIImageView alloc] init];
    self.photoImage.image = [UIImage imageNamed:@"login-6"];
    [self.view addSubview:self.photoImage];
    [self.photoImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(100);
        make.top.equalTo(self.view.mas_top).offset(30+kNavbarAndStatusBar);//80
        make.centerX.equalTo(self.view);
    }];
    
    UIImageView *bgView = [[UIImageView alloc] init];
    bgView.image = [UIImage imageNamed:@"login-3"];
//    bgView.contentMode = UIViewContentModeRedraw;
    
//    bgView.layer.borderWidth = 1;
//    bgView.layer.borderColor = Bottom_Line_Color.CGColor;
    bgView.userInteractionEnabled = YES;
    bgView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(10);
        make.top.equalTo(self.photoImage.mas_bottom).offset(30);//45
        make.centerX.equalTo(self.view);
        make.height.offset(kBgViewHeight);
    }];
    
    UILabel *phoneLabel = [[UILabel alloc] init];
    phoneLabel.text = @"手机号码";
    phoneLabel.textColor = Text_Color_090909;
    phoneLabel.font = BHFont_Size_15;
    [bgView addSubview:phoneLabel];
    [phoneLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bgView.mas_left).offset(kLeftMarginHeight);
        make.top.equalTo(bgView.mas_top).offset(kTopMarginHeight);
//        make.width.offset(65);
        make.width.offset([BHSettingUtil widthForText:@"手机号码" fontSize:15]-10);
    }];
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = Bottom_Line_Color;
    [bgView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bgView.mas_left).offset(kLeftMarginHeight);
        make.height.offset(0.5);
        make.centerX.equalTo(bgView);
        make.centerY.equalTo(bgView);
    }];
    
    UILabel *pswLabel = [[UILabel alloc] init];
    pswLabel.text = @"登录密码";
    pswLabel.textColor = Text_Color_090909;
    pswLabel.font = BHFont_Size_15;
    [bgView addSubview:pswLabel];
    [pswLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bgView.mas_left).offset(kLeftMarginHeight);
        make.bottom.equalTo(bgView.mas_bottom).offset(-kTopMarginHeight);
        make.width.equalTo(phoneLabel.mas_width);
    }];
    
    self.phoneTF = [[UITextField alloc] init];
    self.phoneTF.placeholder = @"请输入手机号";
    self.phoneTF.font = BHFont_Size_15;
    self.phoneTF.keyboardType = UIKeyboardTypePhonePad;
    [bgView addSubview:self.phoneTF];
    [self.phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(phoneLabel.mas_right).offset(0);//25
        make.right.equalTo(line.mas_right);
        make.centerY.equalTo(phoneLabel);
        make.height.offset(50);
    }];
    
    self.pswTF = [[UITextField alloc] init];
    self.pswTF.placeholder = @"请输入密码";
    self.pswTF.font = BHFont_Size_15;
    self.pswTF.secureTextEntry = YES;
    [bgView addSubview:self.pswTF];
    [self.pswTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.phoneTF.mas_left);
        make.right.equalTo(self.phoneTF.mas_right);
        make.centerY.equalTo(pswLabel);
        make.height.offset(50);
    }];
    
    self.loginBtn = [[UIButton alloc] init];
    [self.loginBtn setBackgroundColor:Bg_Color_333333];
    [self.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [self.loginBtn setTitleColor:Text_Color_FFFFFF forState:UIControlStateNormal];
    [self.loginBtn addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    self.loginBtn.titleLabel.font = BHFont_Size_17;
    self.loginBtn.layer.masksToBounds = YES;
    self.loginBtn.layer.cornerRadius = 10;
    [self.view addSubview:self.loginBtn];
    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(10);
        make.top.equalTo(bgView.mas_bottom).offset(50);//80
        make.centerX.equalTo(self.view);
        make.height.offset(55);
    }];
    
    self.registBtn = [[UIButton alloc] init];
    [self.registBtn setTitle:@"快速注册" forState:UIControlStateNormal];
    [self.registBtn setTitleColor:Text_Color_333333 forState:UIControlStateNormal];
    [self.registBtn addTarget:self action:@selector(registAction) forControlEvents:UIControlEventTouchUpInside];
    self.registBtn.titleLabel.font = BHFont_Size_15;
    [self.view addSubview:self.registBtn];
    [self.registBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(10);
        make.top.equalTo(self.loginBtn.mas_bottom).offset(30);//80
        make.centerX.equalTo(self.view);
        make.height.offset(55);
    }];
    
    self.forgetBtn = [[UIButton alloc] init];
    [self.forgetBtn setTitle:@"忘记密码？" forState:UIControlStateNormal];
    [self.forgetBtn setTitleColor:Text_Color_090909 forState:UIControlStateNormal];
    [self.forgetBtn addTarget:self action:@selector(forgetPswAction) forControlEvents:UIControlEventTouchUpInside];
    self.forgetBtn.titleLabel.font = BHFont_Size_12;
    [self.view addSubview:self.forgetBtn];
    [self.forgetBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.top.equalTo(bgView.mas_bottom).offset(10);
        make.height.offset(30);
    }];
}

#pragma 按钮事件
- (void)loginAction {
    if ([BHSettingUtil dataAndStringIsNull:self.phoneTF.text]) {
        [[BHAlertUtil alertManager]showPromptInfo:@"请输入手机号"];
    }else if ([BHSettingUtil dataAndStringIsNull:self.pswTF.text]) {
        [[BHAlertUtil alertManager]showPromptInfo:@"请输入密码"];
    }else {
        [self requestPostLogins];
    }
}

- (void)forgetPswAction {
//    __weak typeof(self) weakSelf = self;
    ForgetPswViewController *next = [[ForgetPswViewController alloc]init];
    [self pushViewController:next animated:YES];
}

- (void)registAction {
//    __weak typeof(self) weakSelf = self;
    RegistViewController *next = [[RegistViewController alloc]init];
//    next.block = ^{
//        weakSelf.userModel = [SGUserInfo getUserInfo];
//        weakSelf.phoneTextField.text = weakSelf.userModel.UserPhone;
//        weakSelf.passwordTextField.text = weakSelf.userModel.UserPas;
//    };
    [self pushViewController:next animated:YES];
}

#pragma 接口
- (void)requestPostLogins {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [[BHAlertUtil alertManager]showLoading:nil];
    [params setObject:self.phoneTF.text forKey:@"telno"];
    [params setObject:self.pswTF.text forKey:@"password"];
    [PPHTTPRequest requestPostLogins:^(id response, BOOL success) {
        [[BHAlertUtil alertManager]hiddenLoading];
        if (success) {
            self.userModel = [SGUserModel yy_modelWithJSON:response];
            self.userModel.UserPhone = self.phoneTF.text;
            self.userModel.UserPas = self.pswTF.text;
            [SGUserInfo saveUserInfo:self.userModel];
            [self loginChatAction];
            
            [[BHAlertUtil alertManager]showPromptInfo:@"登录成功"];
//            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInteger:LoginProtocolTypeSuccess],BHLoginRegister_Key, nil];
//            [[NSNotificationCenter defaultCenter] postNotificationName:BHLoginRegister_Key object:nil userInfo:dic];
//            self.loginType == nil ? : self.loginType(LoginProtocolTypeSuccess);
//            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
            
            [self.navigationController popViewControllerAnimated:YES];
        }
    } params:params];
}

#pragma mark - 环信登陆
- (void)loginChatAction {
//    self.userModel = [SGUserInfo getUserInfo];
//    [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:self.userModel.hx_user_name password:self.userModel.hx_password completion:^(NSDictionary *loginInfo, EMError *error) {
//        if (!error && loginInfo) {
//            NSLog(@"登录成功");
//        }
//    } onQueue:nil];
//}

//{
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        self.userModel = [SGUserInfo getUserInfo];
        //保存信息
        NSDictionary *dic = @{@"easemobuserId":self.userModel.hx_user_name,@"userName":[BHSettingUtil dataAndStringIsNull:self.userModel.company_name]?@"":self.userModel.company_name,@"userImage":@""};
        [[ContactDataObject shareInstance]insertData:dic];
        EMError *error = [[EMClient sharedClient]loginWithUsername:self.userModel.hx_user_name password:self.userModel.hx_password];
        dispatch_async(dispatch_get_main_queue(), ^{
//            [weakSelf hideHud];
            if (!error) {
                //自动接群邀请
                [EMClient sharedClient].options.isAutoAcceptGroupInvitation = YES;
                NSLog(@"登录成功");
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    [[EMClient sharedClient]migrateDatabaseToLatestSDK];
                    [[EMClient sharedClient]setApnsNickname:self.userModel.company_name];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        EMPushOptions *options = [[EMClient sharedClient] pushOptions];
                        options.displayStyle = EMPushDisplayStyleMessageSummary;
                        // options.displayStyle == EMPushDisplayStyleSimpleBanner // 显示“您有一条新消息”
                        EMError *error = [[EMClient sharedClient] updatePushOptionsToServer]; // 更新配置到服务器，该方法为同步方法，如果需要，请放到单独线程
                        if(!error) {
                            // 成功
                        }else {
                            // 失败
                        }
                        [[ChatDemoHelper shareHelper]asyncGroupFromServer];
                        [[ChatDemoHelper shareHelper]asyncConversationFromDB];
                        [[ChatDemoHelper shareHelper]asyncPushOptions];
                        //                        [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
                        //发送自动登录状态通知
                        [[NSNotificationCenter defaultCenter]postNotificationName:KNOTIFICATION_LOGINCHANGE object:@([[EMClient sharedClient] isLoggedIn])];
                    });
                });
            }else {
                switch (error.code) {
                    case EMErrorNetworkUnavailable:
                        NSLog(@"No network connection!");
                        break;
                    case EMErrorServerNotReachable:
                        NSLog(@"Connect to the server failed!");
                        break;
                    case EMErrorUserAuthenticationFailed:
                        NSLog(@"-->%@",error.errorDescription);
                        break;
                    case EMErrorServerTimeout:
                        NSLog(@"Connect to the server timed out!");
                        [self loginChatAction];
                        break;
                    default:
                        NSLog(@"Login failure");
                        break;
                }
            }
        });
    });
}


@end
